package com.zhugang.week06;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * @program algorithms
 * @description: levelOrder
 * @author: chanzhugang
 * @create: 2022/07/14 16:50
 */
public class LevelOrder {

    /**
     * 剑指offer 32-I 从上到下打印二叉树(层序遍历)
     *
     * @param root
     * @return
     */
    public int[] levelOrder(TreeNode root) {
        if (root == null) {
            return new int[0];
        }
        // 层序遍历：用队列实现
        List<Integer> list = new ArrayList<>();
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        while (!queue.isEmpty()) {
            TreeNode node = queue.poll();
            list.add(node.val);
            if (node.left != null) {
                queue.add(node.left);
            }
            if (node.right != null) {
                queue.add(node.right);
            }
        }
        // list to array
        int[] resArray = new int[list.size()];
        for (int i = 0; i < list.size(); i++) {
            resArray[i] = list.get(i);
        }
        return resArray;
    }


    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        public TreeNode(int val) {
            this.val = val;
        }
    }

}